package cn.wolf.xml;

import java.io.File;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn.wolf.tools.Log;

public abstract class Parser {
	/**
	 * 转换xml
	 * @param uri 
	 * 		获取xml的uri地址
	 * @return
	 * 		返回相应的实体类列表
	 */
	public List<?> parse(String uri) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			Document document = builder.parse(uri);

			Element root = document.getDocumentElement();

			return traverse(root);

		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("解析xml异常，异常为：" + ex);
		}

		return Collections.emptyList();
	}
	
	/**
	 * 转换xml
	 * @param uri 
	 * 		获取xml的uri地址
	 * @return
	 * 		返回相应的实体类列表
	 */
	public List<?> parse(File file) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			Document document = builder.parse(file);

			Element root = document.getDocumentElement();

			return traverse(root);

		} catch (Exception ex) {
			Log.e("解析xml异常，异常为：" + ex);
		}

		return Collections.emptyList();
	}
	
	/**
	 * 转换xml
	 * @param uri 
	 * 		获取xml的uri地址
	 * @return
	 * 		返回相应的实体类列表
	 */
	public List<?> parse(InputStream stream) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			Document document = builder.parse(stream);

			Element root = document.getDocumentElement();

			return traverse(root);

		} catch (Exception ex) {
			Log.e("解析xml异常，异常为：" + ex);
		}

		return Collections.emptyList();
	}
	
	
	/**
	 * 遍历子项
	 * @param root
	 * 		xml根元素
	 * @return
	 * 		实体类列表
	 */
	protected abstract List<?> traverse(Element root);
}
